import {NB_AUTH_OPTIONS} from "@nebular/auth";
import {Component, Inject} from "@angular/core";
import {getDeepFromObject} from "@nebular/auth/helpers";
import {AdminService} from "../AdminService";
import {Router} from "@angular/router";
import {UserService} from "../UserService";
import {AuthService} from "../energy/api";
import {BaseRequest} from "../utils/BaseRequest";

@Component({
  templateUrl: './login-component.html'
})
export class LoginComponent {
  showMessages: { error: boolean, success: boolean };
  errors: string[] = [];
  messages: string[] = [];
  submitted: boolean = false;
  user: { email: string, password: string, rememberMe: boolean } = {email: '', password: '', rememberMe: false};
  rememberMe: boolean;
  isAdmin:boolean;
  constructor(@Inject(NB_AUTH_OPTIONS) protected options = {}, private admin: AdminService,private userService:UserService, private api: AuthService, private router: Router) {
    this.showMessages = this.getConfigValue('forms.login.showMessages');
    this.rememberMe = this.getConfigValue('forms.login.rememberMe');
  }

  login() {
    console.log(this.user);
    if(this.isAdmin) {
      this.api.postECALogin(new BaseRequest(
        {
          username: this.user.email,
          password: this.user.password
        }
      )).toPromise().then(res => {
        if (res.success) {
          this.admin.setAdmin(JSON.parse(res.message));
          console.log(this.admin.getAdmin());
          this.messages.push("登录成功");
          this.showMessages.success = true;
          this.router.navigate(['/pages']);
        } else {
          this.errors.push(res.message);
          this.showMessages.error = true
        }
      })
    }else{
      const req = new BaseRequest({
        username: this.user.email,
        password: this.user.password
      });
      req.sysId = "0";
      this.api.postECALogin(req).toPromise().then(res => {
        if (res.success) {
          this.userService.setUser(JSON.parse(res.message));
          this.messages.push("登录成功");
          this.showMessages.success = true;
          this.router.navigate(['/pages']);
        } else {
          this.errors.push(res.message);
          this.showMessages.error = true
        }
      })
    }
  }

  getConfigValue(key: string): any {
    return getDeepFromObject(this.options, key, null);
  }
}
